#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>


/**
 * socket 客户端
 * @return
 */
int main() {

    int ret = -1;

    //创建套接字
    int socket_fd = socket(AF_INET,SOCK_STREAM,0);
    if(socket_fd == -1){
        perror("socket");
        goto error;
    }
    //链接服务器
    // IP4 协议 套接字结构体
    struct sockaddr_in addr;
    //IP4 协议 套接字结构体 协议
    addr.sin_family = AF_INET;
    //IP4 协议 套接字结构体 端口
    addr.sin_port = htons(8080);
    //IP4 协议 套接字结构体 ip地址
    inet_pton(AF_INET,"192.168.1.1",&addr.sin_addr.s_addr);
    ret = connect(socket_fd,(struct sockaddr *)&addr, sizeof(addr));
    if(ret == -1){
        perror("connect");
        return 1;
    }
    //读写数据
    char buff[1024] = "";
    while(1){
        //bzero(buff, sizeof(buff));
        memset(buff,0, sizeof(buff));
        int n = read(STDIN_FILENO,buff, sizeof(buff));
        if(n == -1){
            perror("read");
            goto error;
        }
        write(socket_fd,buff, n);
        memset(buff,0, sizeof(buff));
        n = read(socket_fd,buff, sizeof(buff));
        write(STDOUT_FILENO,buff,n);

    }

    //关闭

    close(socket_fd);
    return 0;
    error : close(socket_fd);
    return 1;
}

